
const fs = require('fs');
const path = require('path');
const chalk = require('chalk'); //命令行输出样式美化
const inquirer = require('inquirer'); //命令行交互
const checkDire = require('../utils/checkDire.js');
const { exec } = require('child_process');
const { promptTypeList } = require('../config.js');
const config = require('../config.js');
module.exports = async (projectName,cmd) => {
      await checkDire(path.join(process.cwd(),projectName),projectName);   // 检测创建项目文件夹是否存在
      inquirer.prompt(promptTypeList).then(result => { //inquirer 交互问答
        const {url, gitName, val} = result.type;
        console.log("您选择的模版类型信息如下：" + val);
        console.log('项目初始化拷贝获取中...');
        if(!url){
          console.log(chalk.red(`${val} 该类型暂不支持...`));
          process.exit(1);
        }
        exec('git clone ' + url, function (error, stdout, stderr) {  //git仓库代码下载
          if (error !== null) {
            console.log(chalk.red(
              `clone fail,${error}`
            ));
            return;
          }
          const newPath = path.join("src/viewsPackages/", projectName) 
          console.log(gitName, 'gitName===')
          //这里先要创建文件夹
          fs.rename(gitName, newPath, (err)=>{
            if (err) {
              exec('rm -rf '+gitName, function (err, out) {});
              console.log(chalk.red(`The ${projectName} project template already exist`));
            } else {
              console.log(chalk.green(`✔ The ${projectName} project template successfully create(项目模版创建成功)`));
              generateEnv(projectName,result)
              generateBuildCmd(projectName)
              upDateConfig(projectName)
            }
          });
        });

        // //fs 生成环境变量配置文件
        // var writeStream = fs.createWriteStream(".env."+projectName);
        //   writeStream.write("# NODE 环境 \n");
        //   writeStream.write("NODE_ENV = "+result.env+" \n\n");
        //   writeStream.write("# 项目名称 \n");
        //   writeStream.write("VUE_APP_TITLE = "+projectName+"-Me \n\n");
        //   writeStream.write("VUE_APP_CLIENT_VERION = "+result.version+" \n\n");
        //   writeStream.write("VUE_APP_BASE_URL = '"+result.baseUrl+"' \n\n");
        //   writeStream.write("VUE_APP_QUICK_URL = '"+result.quickUrl+"' \n\n");
        //   writeStream.end();


          //  //生成打包，服务启动的命令行
          // fs.readFile('./package.json', "utf8", function(err, data) {
          //   if (err) {
          //       throw new Error("读取文件失败");
          //   }
          //   const dataJson = JSON.parse(data)
          //   const { scripts } = dataJson
          //   const serKey = "serve-"+projectName
          //   const serveCmd = "vue-cli-service serve --dir " + projectName + " --build "+ projectName
          //   const buildTestKey = "build-"+projectName+":test"
          //   const buildTestCmd = "vue-cli-service build --dir " + projectName + " --mode commontest"
          //   const buildKey = "build-"+projectName
          //   const buildCmd = "vue-cli-service build --dir " + projectName + " --mode "+ projectName
          //   scripts[serKey] = serveCmd
          //   scripts[buildTestKey] = buildTestCmd
          //   scripts[buildKey] = buildCmd
          //   fs.writeFile('./package.json', JSON.stringify(dataJson,"","\t"), "utf-8", function(err) {
          //       if (err) {
          //           throw new Error("package.json生成打包指令失败");
          //       } else {
          //           console.log("package.json生成打包指令成功");
          //       }
          //   });
          // });


          //写入当前一些配置文件指令
          // console.log(config.serveList[], 'config.serveList.choices==')
          // config.js
          // config.serveList[0].choices.push(projectName)
          // config.buildCheckbox[0].choices.push(projectName)
          
          // fs.writeFile(__dirname + '/../config.js', "module.exports  ="+JSON.stringify(config,"","\t"), 'utf-8', (err) => {
          //   if (err) console.log(err)
          //   console.log(chalk.green('New template added!\n'))
          //   console.log(chalk.grey('The last template list is: \n'))
          //   console.log(config.buildCheckbox[0].choices)
          //   console.log('\n')
          //   // process.exit()
          // })
         


        })
    
   
 }


 //fs 生成环境变量配置文件
 const generateEnv = (projectName,result) => {
   //fs 生成环境变量配置文件
   var writeStream = fs.createWriteStream(".env."+projectName);
   writeStream.write("# NODE 环境 \n");
   writeStream.write("NODE_ENV = "+result.env+" \n\n");
   writeStream.write("# 项目名称 \n");
   writeStream.write("VUE_APP_TITLE = "+projectName+"-Me \n\n");
   writeStream.write("VUE_APP_CLIENT_VERION = "+result.version+" \n\n");
   writeStream.write("VUE_APP_BASE_URL = '"+result.baseUrl+"' \n\n");
   writeStream.write("VUE_APP_QUICK_URL = '"+result.quickUrl+"' \n\n");
   writeStream.end();
 }
 
 //生成打包，服务启动的命令行
 const generateBuildCmd = (projectName)=>{
    //生成打包，服务启动的命令行
    fs.readFile('./package.json', "utf8", function(err, data) {
      if (err) {
          throw new Error("读取文件失败");
      }
      const dataJson = JSON.parse(data)
      const { scripts } = dataJson
      const serKey = "serve-"+projectName
      const serveCmd = "vue-cli-service serve --dir " + projectName + " --build "+ projectName
      const buildTestKey = "build-"+projectName+":test"
      const buildTestCmd = "vue-cli-service build --dir " + projectName + " --mode commontest"
      const buildKey = "build-"+projectName
      const buildCmd = "vue-cli-service build --dir " + projectName + " --mode "+ projectName
      scripts[serKey] = serveCmd
      scripts[buildTestKey] = buildTestCmd
      scripts[buildKey] = buildCmd
      fs.writeFile('./package.json', JSON.stringify(dataJson,"","\t"), "utf-8", function(err) {
          if (err) {
              throw new Error("package.json生成打包指令失败");
          } else {
              console.log("package.json生成打包指令成功");
          }
      });
    });

 }
 //写入当前一些配置文件指令
const upDateConfig = (projectName)=>{
  //写入当前一些配置文件指令
  // console.log(config.serveList[], 'config.serveList.choices==')
  // config.js
  config.serveList[0].choices.push(projectName)
  config.buildCheckbox[0].choices.push(projectName)
  
  fs.writeFile(__dirname + '/../config.js', "module.exports  ="+JSON.stringify(config,"","\t"), 'utf-8', (err) => {
    if (err) console.log(err)
    console.log(chalk.green('New template added!\n'))
    console.log(chalk.grey('The last template list is: \n'))
    console.log(config.buildCheckbox[0].choices)
    console.log('\n')
    // process.exit()
  })
}